import React from "react";
import {Form, Popconfirm, Table,} from "antd";
import EditableCell from "../EditableCell/EditableCell";
import './EditableTable.css'

class EditableTable extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            editingKey: '',
            mergedColumns: [],
        }
    }

    form = React.createRef()

    componentDidMount() {
        this.initCols()
    }

    initCols = () => {
        const columns = this.props.columns
        const operationColRender = (_, record) => {
            const editable = this.isEditing(record)
            const edit = <span>
                <a
                    onClick={() => this.save(record.key)}
                    style={{marginRight: 8,}}
                >
                    Save
                </a>
                <Popconfirm title="Sure to cancel?" onConfirm={this.cancel}>
                    <a>Cancel</a>
                </Popconfirm>
            </span>
            const normal = <a
                disabled={this.state.editingKey !== ''}
                onClick={() => this.edit(record)}
            >
                编辑单列
            </a>
            return editable ? edit : normal
        }

        const operationCol = {
            title: '编辑',
            dataIndex: 'operation',
            render: operationColRender
        }

        columns.push(operationCol)
        const mergedColumns = this.mergeColumns(columns)
        this.setState({
            mergedColumns,
        })
    }

    initKey = () => {
        this.setState({
            editingKey: '',
        })
    }

    edit = record => {
        this.form.current.setFieldsValue({ ...record })
        this.setState({
            editingKey: record.key,
        })
    }

    cancel = () => {
        this.setState({
            editingKey: '',
        })
    }

    save = async key => {
        try {
            const data =  this.props.dataSource
            const row = await this.form.current.validateFields();
            const newData = [...data];
            const index = newData.findIndex(item => key === item.key);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row })

                const savePromise = this.props.save({old: data[index], change: row,})
                savePromise.then(() => {
                    this.initKey()
                })

            } else {
                newData.push(row)
                this.setState({
                    editingKey: '',
                })
                // this.props.onSave()
                // this.setState({
                //     pointList: newData,
                // })
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    }


    isEditing = record => record.key === this.state.editingKey

    mergeColumns = cs => {
        const mergedColumns = cs.map(col => {
            if (!col.editable) {
                return col
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                }),
            }
        })
        return mergedColumns
    }

    render() {
        return <div>
            <Form
                ref={this.form}
            >
                <Table
                    components={{
                        body: {
                            cell: EditableCell,
                        },
                    }}
                    bordered
                    rowClassName="editable-row"
                    dataSource={this.props.dataSource}
                    columns={this.state.mergedColumns}
                    pagination={{
                        onChange: this.cancel,
                    }}
                />
            </Form>
        </div>
    }

}
export default EditableTable
